//
//  ZHUserAccount.swift
//  weibosina
//
//  Created by zhangzhen on 16/6/16.
//  Copyright © 2016年 zhangzhen. All rights reserved.
//

import UIKit

class ZHUserAccount: NSObject,NSCoding{
    /*
     "access_token" = "2.00j7rKDD61kyJD83aeaaa07eOPBQeD";
     "expires_in" = 111580;
     "remind_in" = 111580;
     uid = 2795316173;
     */
    
    //定义的过期时间
    var expiresDate : NSDate?
    //过期日期
    var expires_in : NSTimeInterval = 0 {
        didSet{//计算过期的日期
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
            
        }
    }
    var uid : String?
    var access_token : String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    override var description: String {
        let keys = ["access_token", "expires_in", "uid"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    
    //字典转模型
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //为没有定义的键赋值
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //保存当前的对象
    func saveUserAccount() {
        
        // 1. 保存路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        // 2. 从 Xcode 7 beta 5 开始 stringByAppendingPathComponent 转为 NSString 特有
        // 单纯的 as 在 Swift 中大多只有三个地方会用 `桥接`
        // 1> String as NSString
        // 2> NSArray as [array]
        // 3> NSDictionary as [String: AnyObject]
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        
        // 在实际开发中，一定要确认文件真的保存了！
        print(path)
        
        // 3. 归档保存
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }

    
    // MARK: - `键值`归档和解档
    /// 归档 - 在把当前对象保存到磁盘前，将对象编码成二进制数据 － 跟网络的序列化概念很像！
    ///
    /// - parameter aCoder: 编码器
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 解档 - 从磁盘加载二进制文件，转换成对象时调用 － 跟网络的反序列化很像
    ///
    /// - parameter aDecoder: 解码器
    ///
    /// - returns: 当前对象
    /// `required` - 没有继承性，所有的对象只能解档出当前的类对象
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }

}
